package fire.and.near.challenger;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.facebook.Response;

import fire.and.near.challenger.camera.CameraHelper;
import fire.and.near.challenger.database.ChallengeModel;
import fire.and.near.challenger.database.ChallengeModel.ChallengeType;
import fire.and.near.challenger.database.ChallengeStatus;
import fire.and.near.challenger.database.DatabaseActivity;
import fire.and.near.challenger.database.DatabaseAsyncTask;
import fire.and.near.challenger.database.DatabaseAsyncTask.DatabaseQueryOptions;
import fire.and.near.challenger.database.DatabaseResponse;
import fire.and.near.challenger.database.FriendModel;
import fire.and.near.challenger.database.ProfileManager;
import fire.and.near.challenger.facebook.FacebookActionAdapter;
import fire.and.near.challenger.facebook.FacebookHelper;
import fire.and.near.challenger.facebook.MessageBuilder;
import fire.and.near.challenger.facebook.MessageType;
import fire.and.near.challenger.util.Consts;
import fire.and.near.challenger.web.HttpRequestSender;

public class CustomChallengeActivity extends Activity implements DatabaseActivity {

	private String mCurrentPhotoPath = null;
	private FacebookHelper mFbHelper = LoginActivity.mFbHelper;
	private ChallengeModel mChallenge = null;
	private boolean isWorking = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_complete_challenge);

		final Activity context = this;
		
		findViewById(R.id.textView_descr).setVisibility(View.GONE);

		ImageView ivPreview = (ImageView) findViewById(R.id.imageView_photo);
		ivPreview.setImageDrawable(getResources().getDrawable(R.drawable.camera_placeholder));
		ivPreview.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				
				if (isWorking) {
					return;
				}
				
				mCurrentPhotoPath = CameraHelper
						.dispatchTakePictureIntent(context);
			}
		});
		
		((EditText) findViewById(R.id.editText_challenge_text))
			.addTextChangedListener(new TextWatcher() {
				
				@Override
				public void onTextChanged(CharSequence s, int start, int before, 
						int count) {
					if (s.length() >= Consts.MESSAGE_MAX_LENGTH)
			        {
			            Toast.makeText(context, 
			            		"Challenge description can't be longer than " + Consts.MESSAGE_MAX_LENGTH + " letters", 
			            		Toast.LENGTH_LONG).show();
			        }
				}
				
				@Override
				public void beforeTextChanged(CharSequence s, int start, int count,
						int after) { }
				
				@Override
				public void afterTextChanged(Editable s) { }
			});

		Button btnCompleteChallenge = (Button) findViewById(R.id.button_complete_challenge);

		btnCompleteChallenge.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				
				EditText txtChallengeDescription = (EditText) findViewById(R.id.editText_challenge_text);
				String answer = txtChallengeDescription.getText()
						.toString().trim();
				if (answer.length() == 0) {
					Toast.makeText(context, "Please fill in your answer",
							Toast.LENGTH_LONG).show();
					return;
				}

				// ignore spamming button click
				if (isWorking) {
					return;
				}
				
				isWorking = true;
				
				findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
				
				mChallenge = new ChallengeModel();
				mChallenge.setAnswer(answer);
				
				long myFbId = 0;
				
				if (HttpRequestSender.isNetworkAvailable(context)) {
					myFbId = mFbHelper.getMyFacebookId();
				} else {
					myFbId = new ProfileManager(context).getFbId();
				}
				
				mChallenge.setChallengedID(myFbId);
				mChallenge.setChallenger(new FriendModel(myFbId));
				mChallenge.setHashtag(Consts.DEFAULT_HASHTAG);
				mChallenge.setAccepted(true);
				mChallenge.setStatus(ChallengeStatus.PENDING_FOR_FACEBOOK);
				
				if (mCurrentPhotoPath != null) {
					mChallenge.setPhotoPath(mCurrentPhotoPath);
					mChallenge.setChallengeType(ChallengeType.PHOTO);
				} else {
					mChallenge.setChallengeType(ChallengeType.TEXT);
				}
				
				List<ChallengeModel> challenges = new ArrayList<ChallengeModel>();
				challenges.add(mChallenge);
				
				new DatabaseAsyncTask(context, DatabaseQueryOptions.INSERT_CHALLENGES).execute(challenges);

			}
		});
	}
	
	@Override
	public void processDatabaseResponse(DatabaseResponse result) {
		if (result.isSuccessful()) {
			switch (result.getOption()) {
			case INSERT_CHALLENGES:
				if (result.isSuccessful()) {
					
					mChallenge.setID(((Long)result.getData()).intValue());

					if (mChallenge.getStatus() == ChallengeStatus.PENDING_FOR_FACEBOOK) {
						Bitmap bitmap = null;
						
						if (!HttpRequestSender.isNetworkAvailable(this)) {
							Toast.makeText(	this, 
											"No Internet access. Marked as 'pending'.", 
											Toast.LENGTH_LONG)
												.show();
							finish();
							return;
						}
						
						if (mChallenge.getChallengeType() == ChallengeType.PHOTO && mCurrentPhotoPath == null) {
							Toast.makeText(this, "No photo",
									Toast.LENGTH_LONG).show();
							return;
						}
						
						if(mCurrentPhotoPath != null) {
							bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
						}
					
					
					MessageBuilder msgBuilder = null;
	
					msgBuilder = new MessageBuilder(null, 
														mChallenge.getAnswer(), 
														Consts.DEFAULT_HASHTAG, 
														MessageType.SelfChallenge);
					
					final Activity context = this;
					
					mFbHelper.postStatusUpdate(	context, 
							msgBuilder.build(), 
							null, 
							bitmap, 
							new FacebookActionAdapter() {
								@Override
								public void onActionCompleted(
										Response response) {
									
									if (response.getError() == null) {
										Log.i("UploadStatusWithPic",
												"Success");
										Toast.makeText(
												context,
												"Posted on facebook",
												Toast.LENGTH_LONG)
												.show();
										
										new DatabaseAsyncTask(
												context,
												DatabaseQueryOptions.COMPLETE)
												.execute(mChallenge
														.getID());
									} else {
										Log.i("UploadStatusWithPic",
												response.toString());
									}
								}
							}
					);
					}
				}
				break;
			case COMPLETE:
				Toast.makeText(this, "Challenge added to history",
						Toast.LENGTH_LONG).show();
				finish();
				break;
			default:
				break;
			}
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (HttpRequestSender.isNetworkAvailable(this)) {
			mFbHelper.onActivityResult(this, requestCode, resultCode, data);
		}
		
		if (requestCode == CameraHelper.REQUEST_TAKE_PHOTO) {
			ImageView ivPreview = (ImageView) findViewById(R.id.imageView_photo);
			
			if (resultCode == RESULT_OK) {

				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inJustDecodeBounds = true;
				
				BitmapFactory.decodeFile(mCurrentPhotoPath,
						options);
				
				int width = ivPreview.getWidth();
				int height = ivPreview.getHeight();
	
				options = CameraHelper
						.makeSampleOptions(this, options, width, height);
				
				options.inJustDecodeBounds = false;

				final Bitmap bitmap = BitmapFactory.decodeFile(
						mCurrentPhotoPath, options);
	
				ivPreview.setImageBitmap(bitmap);
			} else {
				ivPreview.setImageDrawable(getResources().getDrawable(R.drawable.camera_placeholder));
			}
		}
	}

	@Override
	public void setDatabaseWorking(boolean working) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_logout) {
			if (HttpRequestSender.isNetworkAvailable(this)) {
				LoginActivity.mFbHelper.logout();
			}
			finish();
			return true;
		}
		
		if (id == R.id.action_details) {
			Intent i = new Intent(this, UserDetailsActivity.class);
			startActivity(i);
			
			return true;
		}
		
		return super.onOptionsItemSelected(item);
	}
}
